import store from "@/vuex/store.js"
import {createXHR} from "@/common/js/base/createXHR.js"
let blob = null;

function getBase64Image(img) {
  var imgs = document.createElement("img");
  imgs.src = img;
  var canvas = document.createElement("canvas"), //创建canvas元素
    width = imgs.width, //确保canvas的尺寸和图片一样
    height = imgs.height;
  canvas.width = width;
  canvas.height = height;
  canvas.getContext("2d").drawImage(imgs, 0, 0, width, height); //将图片绘制到canvas中
  var dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
  // return dataURL
  dataURItoBlob(dataURL)
}

function getBase64(url,fun) {
  plus.io.resolveLocalFileSystemURL(url, function (entry) {
    entry.file(function (file) {
      let fileReader = new plus.io.FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onloadend = function (p) {
        let dataURL = p.target.result.toString();
        // return imgbase64
        dataURItoBlob(dataURL,msg=>{
          fun(msg)
        })
      }
    })
  });
};

function dataURItoBlob(base64Data,fun) {
  var byteString;
  if (base64Data.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(base64Data.split(',')[1]);
  else
    byteString = unescape(base64Data.split(',')[1]);
  var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  blob = new Blob([ia], {type: mimeString});
  fun(blob)
}



function upload1(fileType,e,fun,name) {
  let url = null;
  var formData = new FormData();
  formData.append("fileType",fileType);
  formData.append(e.type, blob, name);

  var xhr = createXHR();
  xhr.onreadystatechange = function () {
    if((xhr.status>=200&&xhr.status<300)||xhr.status == 304){
      let imgUrl = JSON.parse(xhr.responseText).data;
      fun(imgUrl);
      store.commit("issueCover",null);
      url = imgUrl
    }
  };
  xhr.open('POST',store.state.ip + "/card/upload", false);
  xhr.setRequestHeader("authorization", localStorage.userid + "_" + store.state.token);
  xhr.send(formData);
  return url
}


export function upload(e,fun) {
  let fileType = null;    //图片值为1，音频值为2，视频值为3
  let name = e.name;
  let imgUrl = null;
  if(e.path.indexOf('jpg')!=-1||e.path.indexOf('png')!=-1){
    fileType = 1;
    getBase64(e.path,msg=>{
      upload1(fileType,msg,f=>{
        fun(f)
      },name);
    })
  }else if(e.path.indexOf('amr')!=-1||e.path.indexOf('mp3')!=-1){
    fileType = 2;
    getBase64(e.path,msg=>{
      upload1(fileType,msg,f=>{
        fun(f)
      },name);
    })
  }else {
    fileType = 3;
    getBase64(e.path,msg=>{
      upload1(fileType,msg,f=>{
        fun(f)
      },name);
    })
  }
  // let base64 = getBase64Image(url);
  // let blob = dataURItoBlob(base64);
  // setTimeout(()=>{

    // console.log('123',imgUrl)
    // return imgUrl
  // },500)
  // let imgUrl = upload1(blob);


}
